<template>
  <HeaderComponent /> <!-- 顶部导航栏 -->
  <div id="checkout">

    <!-- 返回购物车链接 -->
    <div id="BackLink">
      <router-link to="/cart">Return to Shopping Cart</router-link>
    </div>

    <div id="Catalog">
      <h2>Checkout Summary</h2>
      <table>
        <thead>
          <tr>
            <th>Item ID</th>
            <th>Product ID</th>
            <th>Description</th>
            <th>In Stock?</th>
            <th>Quantity</th>
            <th>List Price</th>
            <th>Total Cost</th>
          </tr>
        </thead>
        <tbody>
          <tr v-for="cartItem in cartItems" :key="cartItem.itemId">
            <td>
              <router-link :to="`/item/${cartItem.itemId}`">
                {{ cartItem.itemId }}
              </router-link>
            </td>
            <td>{{ cartItem.item.productId }}</td>
            <td>
              {{ cartItem.item.attribute1 }} {{ cartItem.item.attribute2 }}
              {{ cartItem.item.attribute3 }} {{ cartItem.item.attribute4 }}
              {{ cartItem.item.attribute5 }} {{ products[cartItem.item.productId]?.productName || '' }}
            </td>
            <td>{{ cartItem.inStock ? "Yes" : "No" }}</td>
            <td>{{ cartItem.number }}</td>
            <td>{{ formatCurrency(cartItem.item.listPrice) }}</td>
            <td>{{ formatCurrency(cartItem.total) }}</td>
          </tr>
          <tr>
            <td colspan="7">Sub Total: {{ formatCurrency(subTotal) }}</td>
          </tr>
          <tr v-if="selectedCouponId">
            <td colspan="7">Final Total after Coupon: {{ formatCurrency(finalTotal) }}</td>
          </tr>
        </tbody>
      </table>
    </div>

    <!-- 替换 router-link 为按钮 -->
    <button class="Button" @click="goToOrderTabs">Create Order</button>
  </div>
</template>

<script setup>
import { ref, onMounted, computed } from "vue";
import { useRoute, useRouter } from "vue-router";
import request from '@/utils/request';
import { createOrder } from '@/api/order'; // 请求 createOrder 接口
import HeaderComponent from '@/components/Header.vue';
import "@/assets/css/global.css";

const route = useRoute();
const router = useRouter();

const cartItems = ref([]);
const products = ref({});
const subTotal = ref(0);
const username = ref("");
const couponList = ref([]);
const selectedCouponId = ref(Number(route.query.couponId) || null);

// 获取数据
onMounted(async () => {

  subTotal.value = Number(route.query.subTotal || 0);
  selectedCouponId.value = Number(route.query.couponId || null);
  
  try {
    const couponRes = await request.get("/cart/coupons");
    if (couponRes.status === 0) {
      couponList.value = couponRes.data;
    }

    const cartResponse = await request.get("/cart");
    cartItems.value = cartResponse.data.cartItems;
    subTotal.value = cartResponse.data.total;

    // 获取产品名称
    const productMap = {};
    for (const cartItem of cartItems.value) {
      const categoryId = cartItem.item.productId.split('-')[0];
      const productId = cartItem.item.productId;
      const productRes = await request.get(`/product/${categoryId}/${productId}`);
      if (productRes.status === 0) {
        productMap[productId] = productRes.data;
      }
    }

    products.value = productMap;
    username.value = localStorage.getItem('username') || route.query.username;
  } catch (error) {
    console.error("Failed to load checkout data:", error);
  }
});

const formatCurrency = (value) => {
  return new Intl.NumberFormat("en-US", {
    style: "currency",
    currency: "USD",
  }).format(value);
};

const finalTotal = computed(() => {
  const coupon = couponList.value.find(c => c.id === selectedCouponId.value);
  if (!coupon || subTotal.value < coupon.limit) return subTotal.value;

  if (coupon.deduction > 0) {
    return Math.max(subTotal.value - coupon.deduction, 0);
  }

  if (coupon.discount > 0) {
    return subTotal.value * coupon.discount;
  }

  return subTotal.value;
});

// 👇 跳转到 OrderTabs 页面，携带 state 参数
const goToOrderTabs = () => {
  const orderData = {
    cartItems: cartItems.value,
    finalTotal: finalTotal.value,
    subTotal: subTotal.value,
    selectedCouponId: selectedCouponId.value,
    couponList: couponList.value
  };
  
  sessionStorage.setItem('checkoutData', JSON.stringify(orderData));
  router.push({ name: 'OrderTabs' });
};

//创建订单
async function handleCreateOrder() {
  const username = getCurrentUsername(); // 从 token 或 session 中拿
  const res = await createOrder(username);
  if (res.status === 0) {
    const orderId = res.data.orderId;
    router.push(`/order/ordertabs/${orderId}`); // 跳转到订单编辑页
  } else {
    ElMessage.error(res.message || '创建订单失败');
  }
}


// 新增 checkout 方法
const checkout = () => {
  router.push({ path: '/checkout', query: { 
    username: localStorage.getItem('username'),
    couponId: selectedCouponId.value,
    subTotal: subTotal.value  // ✅ 新增
  }});
};

</script>

<style scoped>
@import "@/assets/css/global.css";
.Button {
  display: inline-block;
  background-color: #f1c40f; /* 明亮的黄色 */
  color: #fff; /* 白色文字 */
  padding: 10px 20px;
  margin-top: 20px;
  text-align: center;
  font-size: 16px;
  border-radius: 6px;
  border: none;
  cursor: pointer;
  transition: background-color 0.3s ease;
}

.Button:hover {
  background-color: #d4ac0d; /* 稍暗一点的黄色做 hover 效果 */
}

</style>
